//
//  IncomingViewController.m

//  SIPphone//
//  Created by wrt on 13-10-28.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//  接听的界面

#import "IncomingViewController.h"
#import "SoundEngine.h"
#import "NSTimer+Pausing.h"

#define INCOMINGNOTANSWER 100001
#define INCOMINGANSWER 100002

//自己写了时间显示  把时分秒定义了出来
static int sec1;
static int sec2;
static int min1;
static int min2;
static int hour1;
static int hour2;

@interface IncomingViewController ()
{
    bool isSpeaker;    //判断是否打开了免提
    bool isUnlock;     //判断是否开了锁
    bool isEnlarge;             //是否放大
    CGRect origiRect;          //用于存放初始的视频框架大小
}

@end

@implementation IncomingViewController
@synthesize inCallTimer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//当界面切出时的操作
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.inCallTimer invalidate];         //关掉计时器
    UIDevice *_curDevice = [UIDevice currentDevice];   //获取设备信息
    [_curDevice setProximityMonitoringEnabled:NO];     //关闭距离传感器
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CALLSTATUSINFO" object:nil];
    
    //屏幕关闭长亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface setWindownId:nil];
    [interface setPreviousWindowId:nil];
    
    //做一个是否开通话中的标记
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"NO" forKey:@"ISINCALLSTATENOW"];
    
    [[SoundEngine shareSound] LoudSpeaker:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //当页面出现时需要再次设置SIP的代理和视频窗口。不然会崩溃。
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    
    //播放铃声
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue,^{
        [[SoundEngine shareSound] returnSetCategory];
        [[SoundEngine shareSound] PlayIncomingTone];
        
        [[SoundEngine shareSound] LoudSpeaker:YES];
        isSpeaker = YES;
    });
    
    //做一个是否开通话中的标记
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"YES" forKey:@"ISINCALLSTATENOW"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //双击手势
//    UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapClick)];
//    [doubleTapGesture setNumberOfTapsRequired:2];
//    [doubleTapGesture setNumberOfTouchesRequired:1];
//    [self.otherPeopleView addGestureRecognizer:doubleTapGesture];
    origiRect = self.otherPeopleView.frame;
    
    
    
    //当页面出现时需要再次设置SIP的代理和视频窗口。不然会崩溃。
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    [interface setWindownId:self.otherPeopleView];
    [interface setPreviousWindowId:self.myselfView];
    self.nameLabel.text = interface.incomingNumber;
    if (interface.incomingDisplayName.length > 0)
    {
        self.displayNameLabel.text = interface.incomingDisplayName;
    }
    
    
    //设置无背景和透明
    [self.statusWebView setBackgroundColor:[UIColor clearColor]];
    [self.statusWebView setOpaque:NO];
    //先判断是否开启了显示开关 若开启则显示
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *isDisplayCallStatus = [[NSString alloc] init];
    isDisplayCallStatus = [defaults objectForKey:@"SAVEISDISPLAYCALLSTATUS"];
    if ([isDisplayCallStatus isEqualToString:@"YES"])
    {
        [self.statusWebView setHidden:NO];
    }
    else
    {
        [self.statusWebView setHidden:YES];
    }
    //显示状态的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusInfo:) name:@"CALLSTATUSINFO" object:nil];
    
    
    //实例化计时器
    inCallTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(incallTime) userInfo:nil repeats:YES];
    //线程循环
    [[NSRunLoop currentRunLoop] addTimer:self.inCallTimer forMode:NSDefaultRunLoopMode];
    //用类别，写了计时器的两个新方法，暂停和继续，类别的头文件和实现文件在extraFiles里面
    [self.inCallTimer pause];
    
    
    //屏幕开启长亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    //靠近屏幕会变黑
    UIDevice *_curDevice = [UIDevice currentDevice];
    [_curDevice setProximityMonitoringEnabled:YES];
    NSNotificationCenter *_defaultCenter = [NSNotificationCenter defaultCenter];
    [_defaultCenter addObserverForName:UIDeviceProximityStateDidChangeNotification
                                object:nil
                                 queue:[NSOperationQueue mainQueue]
                            usingBlock:^(NSNotification *note) {
                                if (_curDevice.proximityState == YES) {
                                    
                                }
                                else {
                                    
                                }
                            }]; 
}

//双击事件处罚
- (void)doubleTapClick
{
    NSLog(@"test111");
    isEnlarge = !isEnlarge;
    if (isEnlarge)  //放大
    {
        [self.otherPeopleView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }
    else            //缩小
    {
        [self.otherPeopleView setFrame:origiRect];
    }
}

//接听按钮操作
- (IBAction)answerButtonPressed:(id)sender
{
    [self.endButton setHidden:YES];
    [self.answerButton setHidden:YES];
    [self.bigEndButton setHidden:NO];
    
    [[SoundEngine shareSound] StopIncomingTone];
    [[SoundEngine shareSound] LoudSpeaker:NO];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:INCOMINGANSWER forKey:@"INCOMINGANSWERSTATUS"];
    [defaults synchronize];
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface answer_call];
    [interface setWindownId:self.otherPeopleView];
    [interface setPreviousWindowId:self.myselfView];

}
//开锁按钮操作
- (IBAction)unlockButtonPressed:(id)sender
{
//    NSLog(@"%@",tempStr);
    
    isUnlock = !isUnlock;
    if (isUnlock)
    {
        [self.isUnlockButton setBackgroundImage:[UIImage imageNamed:@"开锁.png"] forState:UIControlStateNormal];
        [self.isUnlockButton setBackgroundImage:[UIImage imageNamed:@"开锁h.png"] forState:UIControlStateHighlighted];
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface callunlock];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"Unlock success", @"开锁成功 Unlock success") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [alert dismissWithClickedButtonIndex :0 animated:YES];
    }
    else
    {
        [self.isUnlockButton setBackgroundImage:[UIImage imageNamed:@"锁定.png"] forState:UIControlStateNormal];
        [self.isUnlockButton setBackgroundImage:[UIImage imageNamed:@"锁定h.png"] forState:UIControlStateHighlighted];
    }
}
//结束按钮操作
- (IBAction)endButtonPressed:(id)sender
{
    [[SoundEngine shareSound] StopIncomingTone];
    [[SoundEngine shareSound] LoudSpeaker:NO];
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface hang_incoming];
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"Call Endding", @"通话结束 Call Endding") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
//    [alert show];
    //如果是从后台通话时进入了前台 则挂断电话的时候设置到UDP
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *tempIsBackGroundInCall = [[NSString alloc] init];
    tempIsBackGroundInCall = [defaults objectForKey:@"ISBACKGROUNDINCALL"];
    if ([tempIsBackGroundInCall isEqualToString:@"YES"])
    {
        [interface setVideotransport:1];
        [defaults setObject:@"NO" forKey:@"ISBACKGROUNDINCALL"];
        [defaults synchronize];
    }
    
    [self dismissModalViewControllerAnimated:YES];
//    [alert dismissWithClickedButtonIndex :0 animated:YES];
}
- (IBAction)bigEndButton:(id)sender
{
    [[SoundEngine shareSound] StopIncomingTone];
    [[SoundEngine shareSound] LoudSpeaker:NO];
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface hang_incoming];
    
    //如果是从后台通话时进入了前台 则挂断电话的时候设置到UDP
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *tempIsBackGroundInCall = [[NSString alloc] init];
    tempIsBackGroundInCall = [defaults objectForKey:@"ISBACKGROUNDINCALL"];
    if ([tempIsBackGroundInCall isEqualToString:@"YES"])
    {
        [interface setVideotransport:1];
        [defaults setObject:@"NO" forKey:@"ISBACKGROUNDINCALL"];
        [defaults synchronize];
    }
//    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"Call Endding", @"通话结束 Call Endding") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
//    [alert show];
    [self dismissModalViewControllerAnimated:YES];
//    [alert dismissWithClickedButtonIndex :0 animated:YES];
}
//免提按钮操作
- (IBAction)speakerButtonPressed:(id)sender
{
    isSpeaker = !isSpeaker;
    if (isSpeaker)
    {
        [self.isSpeakerButton setBackgroundImage:[UIImage imageNamed:@"免提.png"] forState:UIControlStateNormal];
        [self.isSpeakerButton setBackgroundImage:[UIImage imageNamed:@"免提h.png"] forState:UIControlStateHighlighted];
    }
    else
    {
        [self.isSpeakerButton setBackgroundImage:[UIImage imageNamed:@"听筒.png"] forState:UIControlStateNormal];
        [self.isSpeakerButton setBackgroundImage:[UIImage imageNamed:@"听筒h.png"] forState:UIControlStateHighlighted];
    }
    [[SoundEngine shareSound] LoudSpeaker:isSpeaker];
}

//时间的算法
- (void)incallTime
{
    sec2++;
    if (sec2 == 10)
    {
        sec2 = 0;
        sec1++;
    }
    if (sec1 == 6 && sec2 == 0)
    {
        sec1 = 0;
        min2++;
    }
    if (min2 == 10)
    {
        min2 = 0;
        min1++;
    }
    if (min1 == 6 && min2 == 0)
    {
        min1 = 0;
        hour2++;
    }
    if (hour2 == 10)
    {
        hour2 = 0;
        hour1++;
    }
    NSString *time = [NSString stringWithFormat:@"%i%i:%i%i:%i%i",hour1,hour2,min1,min2,sec1,sec2];
    self.timeLabel.text = time;
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface getCallStatusDetail];
}

- (void)statusInfo:(NSNotification *)notification
{
    NSString *tempHtmlStr = notification.object;
    NSString *webviewText = @"<style>body{margin:0;background-color:transparent;font:14px/6px Custom-Font-Name;color:#ffffff}</style>";
    NSString *htmlString = [webviewText stringByAppendingFormat:@"%@", tempHtmlStr];
    dispatch_async(dispatch_get_main_queue(),^{
        [self.statusWebView loadHTMLString:htmlString baseURL:nil];
    });
}

#pragma mark -
#pragma mark SIPlistenMethod
- (void)callAnswer   //当摘机时
{
    //设置自己和对方的视频到指定的View
    dispatch_async(dispatch_get_main_queue(),^{
        //设置自己和对方的视频到指定的View
        sec1 = 0; sec2 = 0; min1 = 0; min2 = 0; hour1 = 0; hour2 = 0;
        [self.inCallTimer resume]; //计时器继续
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setWindownId:self.otherPeopleView];
        [interface setPreviousWindowId:self.myselfView];
    });
    
    
    //如果是打开扬声器，就让其开启扬声器
    double delayInSeconds = 0.2;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void)
                   {
                       if (isSpeaker == YES)
                       {
                           [[SoundEngine shareSound] LoudSpeaker:YES];
                       }
                   });
}

- (void)callEnding    //当呼叫结束时
{
    //退回之前的界面
    dispatch_async(dispatch_get_main_queue(),^{
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface hang_incoming];
        [self.inCallTimer pause];                     //暂停计时器
        [[SoundEngine shareSound] StopIncomingTone];  //停止铃声
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"Call Endding", @"通话结束 Call Endding") delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
//        [alert show];
        
        //如果是从后台通话时进入了前台 则挂断电话的时候设置到UDP
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *tempIsBackGroundInCall = [[NSString alloc] init];
        tempIsBackGroundInCall = [defaults objectForKey:@"ISBACKGROUNDINCALL"];
        if ([tempIsBackGroundInCall isEqualToString:@"YES"])
        {
            [interface setVideotransport:1];
            [defaults setObject:@"NO" forKey:@"ISBACKGROUNDINCALL"];
            [defaults synchronize];
        }
        
        
        [self dismissModalViewControllerAnimated:YES];
//        [alert dismissWithClickedButtonIndex :0 animated:YES];
    });
}

- (void)openWindow    //视频窗口开始刷新时
{
    //再次指定视频的View
    dispatch_async(dispatch_get_main_queue(),^{
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setWindownId:self.otherPeopleView];
        [interface setPreviousWindowId:self.myselfView];
    });
}


- (void)registerSuccessful //注册成功时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ALERTVIEWCLOSEED" object:nil];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
}

- (void)registerFailed  //注册失败时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
    });
}

//状态信息
- (void)changeStatus:(NSString *)statusStr
{
    dispatch_async(dispatch_get_main_queue(),^{
        
        if ([statusStr rangeOfString:@"contacting you"].location != NSNotFound)
        {
            self.statusLabel.text = NSLocalizedString(@"Ringing", @"对方响铃 Ringing");
            
        }
        
        if ([statusStr isEqualToString:@"Connected."])
        {
            
            self.statusLabel.text = NSLocalizedString(@"Calling", @"正在通话 Calling");
        }
        
        if ([statusStr isEqualToString:@"Call ended"] || [statusStr isEqualToString:@"Call terminated."])
        {
            
            self.statusLabel.text = NSLocalizedString(@"End Call", @"通话结束 End Call");
        }
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//dealloc操作
- (void)dealloc
{
    self.inCallTimer = nil;                  //关闭计时器
    UIDevice *_curDevice = [UIDevice currentDevice];  //获取设备 关闭距离传感器
    [_curDevice setProximityMonitoringEnabled:NO];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CALLSTATUSINFO" object:nil];
}

@end
